package com.fun.feifun.base.utils.format;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.thoughtworks.xstream.XStream;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wukefei
 * @date $ $
 */
public class FormatUtil {

    /**
     * 对象转换成 xml
     * @param item
     * @return
     * @throws IOException
     */
    public static  String convertToXmlX(Object item) throws IOException {
        XStream xstream = new XStream();
        String inputXml = xstream.toXML(item);
        xstream.autodetectAnnotations(true);
        xstream.aliasSystemAttribute(null, "class"); // 去掉 class 属性
        System.out.println(inputXml.toString());
        return inputXml.toString();
    }

    public static  Object xmlConvertToObjX(String xml,Object item) throws IOException {
        XStream xStream = new XStream();
        xStream.processAnnotations(item.getClass()); // 如果User类使用了XStream注解
        return xStream.fromXML(xml);
    }

    // 转换Map到XML字符串的方法
    public static String mapToXml(Map<String, String> map) {
        // 使用JAXBContext来创建Marshaller对象
        try {
            JAXBContext context = JAXBContext.newInstance(Map.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // 创建一个StringWriter用于保存XML
            StringWriter writer = new StringWriter();
            marshaller.marshal(map, writer);
            return writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取指定路径的xml文件转换为Java对象
     *
     * @param xmlPath
     * @param load
     * @return
     */
    public static Object xmlToBean(String xmlPath, Class<?> load) {
        JAXBContext context = null;
        Object object = null;
        try {
            context = JAXBContext.newInstance(load);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            object = unmarshaller.unmarshal(new File(xmlPath));
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * xml字符串转map
     * @param xmlString
     * @return
     * @throws Exception
     */
    public static Map<String, String> convertXmlToMap(String xmlString) throws Exception {
        xmlString=xmlString.replace("gb2312","utf-8");
        byte[] utf8Bytes = xmlString.getBytes(StandardCharsets.UTF_8);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(utf8Bytes));
        Element root = doc.getDocumentElement();
        Map<String, String> map = new HashMap<>();
        NodeList nodeList = root.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            if (nodeList.item(i) instanceof Element) {
                Element element = (Element) nodeList.item(i);
                String value = element.getTextContent();
                map.put(element.getTagName(), value);
            }
        }
        return map;
    }

    public static String objToJson (Object object){
        JSONObject jsonObject = (JSONObject)JSONObject.toJSON(object);
        // 将JSONObject转换为JSON字符串
        String jsonString = jsonObject.toJSONString();
        return jsonString;
    }


    public static String mapToUrlParam (Map<String,String> map){
        StringBuilder sb = new StringBuilder();
        map.forEach((key,value)->{
            sb.append(key+"="+value+"&");
        });
        String substring = sb.substring(0, sb.lastIndexOf("&"));
        return substring;
    }

    public static String mapToXML (Map<String,Object> map,String title){
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=1.0 encoding=utf-8 ?>\n");
        sb.append("<"+title+">\n");
        map.forEach((key,value)->{
            sb.append("<"+key+">");
            sb.append(value);
            sb.append("</"+key+">\n");
        });
        sb.append("</"+title+">");
        return sb.toString();
    }


    public static List<NameValuePair> mapToParam (Map<String,String> map){
        List<NameValuePair> params = new ArrayList<>();
        map.forEach((key,value)->{
            params.add(new BasicNameValuePair(key, value));
        });
        return params;
    }


    /**
     * 对线变成map 对象
     * @author wukefei
     * @date 2024/6/27 10:54
     * @param obj
     * @return Map<Object>
     */
    public static Map<String, Object> objToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 使得私有字段也可以访问
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }


    /**
     * 对线变成map 对象
     * @author wukefei
     * @date 2024/6/27 10:54
     * @param obj
     * @return Map<Object>
     */
    public static Map<String, String> objToMapStr(Object obj) throws IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 使得私有字段也可以访问
            map.put(field.getName(), String.valueOf(field.get(obj)));
        }
        return map;
    }
    /**
     * 对线变成map 对象
     * @author wukefei
     * @date 2024/6/27 10:54
     * @param obj
     * @return Map<Object>
     */
    public static List<NameValuePair> objToParam(Object obj) throws IllegalAccessException {
        List<NameValuePair> params = new ArrayList<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 使得私有字段也可以访问
            params.add(new BasicNameValuePair(field.getName(), String.valueOf(field.get(obj))));
        }
        return params;
    }
}
